﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VM.WebCore.Jwt;

namespace VM.WebCore.SwaggerExtend
{

    /// <summary>
    /// 静态类
    /// </summary>
    public static class SwaggerExtensions
    {

        static List<string> XmlCommentsFilePath
        {
            get
            {
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                DirectoryInfo d = new DirectoryInfo(basePath);
                FileInfo[] files = d.GetFiles("*.xml");
                var xmls = files.Select(a => Path.Combine(basePath, a.FullName)).ToList();
                return xmls;
            }
        }
        /// <summary>
        /// 配置Swagger
        /// </summary>
        /// <param name="service"></param>
        public static void AddSwaggerExt(this IServiceCollection service)
        {
            service.AddEndpointsApiExplorer();
            service.AddSwaggerGen(option =>
            {


                #region 版本的控制
                {

                    foreach (var version in typeof(ApiVersions).GetEnumNames())
                    {
                        //为每个版本做控制
                        option.SwaggerDoc(version, new OpenApiInfo()
                        {
                            Title = "融担发票相关Api文档",
                            Version = version,
                            Description = $"{version}版本：融担发票相关Api文档"
                        });
                    }
                }
                #endregion

                #region 读取注释 
                {
                    //var file = Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml");
                    //// true : 显示控制器层注释
                    //option.IncludeXmlComments(file, true);
                    //option.OrderActionsBy(o => o.RelativePath);
                    foreach (var item in XmlCommentsFilePath)
                    {
                        option.IncludeXmlComments(item);
                    }
                }
                #endregion

                #region 支持jwt token授权
                {
                    //添加安全定义--配置支持token授权机制
                    option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "请输入token,格式为 bearer xxxxxxxx（注意中间必须有空格） " +
                        "  bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoiOEVDMzA2RkEwRkFENEIzQkEwMUUwNzRGMzhGMUZEMUUiLCJpZCI6Imw3Y0pTclFWVnZBVDlkUzZqV1dGYUE9PSIsIm5iZiI6MTcwNTg5MzQ0MiwiZXhwIjoxNzA1ODk0MDQyfQ.cBv2X7mAL2-oE1keM9_xnJKsc-3ugHJtsTK6Ytu2YYc",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        BearerFormat = "JWT",
                        Scheme = "Bearer"
                    });
                    //添加安全要求
                    option.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference =new OpenApiReference()
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id ="Bearer"
                                }
                            },
                            new string[]{ }
                        }
                    });

                    

                   

                };

                #endregion

                {
                    option.SchemaFilter<HideIdPropertiesFilter>();
                }
              
            });
        }

     

            /// <summary>
            /// 
            /// </summary>
            /// <param name="app"></param>
            public static void UseSwaggerExt(this WebApplication app)
        {
           
            app.UseSwagger();
            app.UseSwaggerUI(option =>
            {
                foreach (string version in typeof(ApiVersions).GetEnumNames())
                {
                    option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}版本：财金集团融担发票开具项目的Api文档");
                    
                }
                
            });
        }
        public class HideIdPropertiesFilter : ISchemaFilter
        {
            public void Apply(OpenApiSchema schema, SchemaFilterContext context)
            {
                if (schema.Properties.ContainsKey("id"))
                {
                    var s = schema.Properties["id"].Properties;


                    if (schema.Properties["id"].Equals("onlyInsertIgnore")) {

                        schema.Properties["id"].Nullable = true;
                        schema.Properties["id"].Example = null;
                        schema.Properties["id"].ReadOnly = true;
                        schema.Properties["id"].WriteOnly = false;
                        schema.Properties["id"].Description = "Student identifier (hidden)";
                    }
                   
                }
            }
        }

    }
}
